<?php

namespace book;

class Util
{
    public static function formatPrice($value)
    {
        return round($value, 2);
    }

    public static function getDateTimestamp($time, $timezone = false)
    {
        if (!$timezone) {
            $timezone = config('cashbell.date_timezone');
        }

        $tz = new \DateTimeZone($timezone);
        $t = new \DateTime('@' . $time);
        $t->setTimezone($tz);
        $today = new \DateTime($t->format('m/d/Y'), $tz);
        return $today->getTimestamp();
    }

    public static function getFirstTimestampOfMonth($time, $timezone = false)
    {
        if (!$timezone) {
            $timezone = config('cashbell.date_timezone');
        }

        $tz = new \DateTimeZone($timezone);
        $t = new \DateTime('@' . $time);
        $t->setTimezone($tz);
        $tttt = $t->format('m/1/Y');
        $today = new \DateTime($t->format('m/1/Y'), $tz);
        return $today->getTimestamp();
    }

    public static function removeByKey($arr, $keys)
    {
        foreach ($arr as $key => $value) {
            if (in_array($key, $keys)) {
                unset($arr[$key]);
            }
        }
        return $arr;
    }

    public static function filterByKey($arr, $keys)
    {
        return array_intersect_key($arr, array_flip($keys));
    }

    public static function inviteCode($len = 6)
    {
        $pool = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
        return substr(str_shuffle(str_repeat($pool, ceil($len / strlen($pool)))), 0, $len);
    }

    /**
     * 获取随机红包
     * min<k<max
     * min(n-1) <= money - k <= (n-1)max
     * k <= money-(n-1)min
     * k >= money-(n-1)max
     *
     * @param [type] $money
     * @param [type] $num
     * @param [type] $min
     * @param [type] $max
     * @return void
     */
    public static function getRedPackage($money, $num, $min, $max)
    {
        $data = array();
        if ($min * $num > $money) {
            return array();
        }
        if ($max * $num < $money) {
            return array();
        }
        while ($num >= 1) {
            $num--;
            $kmix = max($min, $money - $num * $max);
            $kmax = min($max, $money - $num * $min);
            $kAvg = $money / ($num + 1);
            //获取最大值和最小值的距离之间的最小值
            $kDis = min($kAvg - $kmix, $kmax - $kAvg);
            //获取0到1之间的随机数与距离最小值相乘得出浮动区间，这使得浮动区间不会超出范围
            $r = ((float)(rand(1, 10000) / 10000) - 0.5) * $kDis * 2;
            $k = round($kAvg + $r, 2);
            $money -= $k;
            $data[] = $k;
        }
        return $data;
    }

    /**
     * 中间加密 用正则
     */
    public static function encryptTel($tel)
    {
        $new_tel = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $tel);
        return $new_tel;
    }

    public static function msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }

    /**
     * 裁图
     */
    public static function cutImg($imgfile, $x = 0, $y = 0, $width = 100, $height = 100)
    {
        //获取原图片的信息
        $imginfo = getimagesize($imgfile);
        //判断图片
        if (!$imginfo) {
            echo "非法图片";
            return false;
        }
        //得到原图宽高
        list($src_w, $src_h) = $imginfo;
        $mime = $imginfo['mime'];
        $arr = explode('/', $mime);
        list($type, $subtype) = $arr;
        //拼接函数名
        $open_img = 'imagecreatefrom' . $subtype;
        $save_img = 'image' . $subtype;
        //打开原图资源
        $img = $open_img($imgfile);
        //创建切图资源
        $cut_img = imagecreatetruecolor($width, $height);
        //切图
        imagecopyresampled($cut_img, $img, 0, 0, $x, $y, $width, $height, $width, $height);
        //获取原图后缀
        $ext = pathinfo($imgfile, PATHINFO_EXTENSION);
        //生成保存路径
        $save_img_name = dirname(__FILE__) . '/../../public/uploads/' . date('YmdHis') . uniqid() . '.' . $ext;
        //保存图片
        $save_img($cut_img, $save_img_name);
        //销毁资源
        imagedestroy($img);
        imagedestroy($cut_img);

        return $save_img_name;
    }

    public static function transparent($imgfile)
    {
        $imgsrc = imagecreatefromjpeg($imgfile);
        //获取原图片的信息
        $imginfo = getimagesize($imgfile);
        //判断图片
        if (!$imginfo) {
            echo "非法图片";
            return false;
        }
        //得到原图宽高
        list($src_w, $src_h) = $imginfo;
        $mime = $imginfo['mime'];
        $arr = explode('/', $mime);
        list($type, $subtype) = $arr;

        //获取原图后缀
        $ext = pathinfo($imgfile, PATHINFO_EXTENSION);

        $imgsrcw = imagesx($imgsrc);
        $imgsrch = imagesy($imgsrc);
        $width = 30;
        $x1 = 2;
        $x2 = $imgsrcw - $x1 - 20;
        $y1 = ($imgsrch - $width) - 2;
        $y2 = $y1 + $width;
        $steps = $x2 - $x1;
        for ($i = 0; $i < $steps; $i++) {
            $alphax = round($i / ($steps / 127)) + 60;
            if ($alphax >= 128)
                $alphax = 127;
            $alpha = imagecolorallocatealpha($imgsrc, 255, 255, 255, $alphax);
            imagefilledrectangle($imgsrc, ($i + $x1), $y1, ($i + $x1 + 1), $y2, $alpha);
        }
        // header('content-type: image/jpeg');
        // imagejpeg($imgsrc);
        $save_img = 'image' . $subtype;
        //生成保存路径
        $save_img_name = dirname(__FILE__) . '/../../public/uploads/' . date('YmdHis') . uniqid() . '.' . $ext;
        $save_img($imgsrc, $save_img_name);
        imagedestroy($imgsrc);

    }

    /**
     * https://www.cnblogs.com/rhythmK/p/5426050.html
     */
    public static function mergeImg()
    {
        $bigImgPath = 'backgroud.png';
        $qCodePath = 'qcode.png';

        $bigImg = imagecreatefromstring(file_get_contents($bigImgPath));
        $qCodeImg = imagecreatefromstring(file_get_contents($qCodePath));

        list($qCodeWidth, $qCodeHight, $qCodeType) = getimagesize($qCodePath);
        // imagecopymerge使用注解
        imagecopymerge($bigImg, $qCodeImg, 200, 300, 0, 0, $qCodeWidth, $qCodeHight, 100);

        list($bigWidth, $bigHight, $bigType) = getimagesize($bigImgPath);


        switch ($bigType) {
            case 1: //gif
                // header('Content-Type:image/gif');
                imagegif($bigImg);
                break;
            case 2: //jpg
                // header('Content-Type:image/jpg');
                imagejpeg($bigImg);
                break;
            case 3: //jpg
                // header('Content-Type:image/png');
                imagepng($bigImg);
                break;
            default:
                # code...
                break;
        }

        imagedestroy($bigImg);
        imagedestroy($qcodeImg);
    }

    /**
     * 文字水印
     */
    public static function watermark($bigImg, $text = 'cashbell')
    {
        $bigImgPath = dirname(dirname(dirname(__FILE__))) . '/public' . $bigImg;
        if (!is_file($bigImgPath)) {
            echo "图片不存在";
            return false;
        }

        $info = pathinfo($bigImgPath);
        $newFile = $info['dirname'] . '/' . $info['filename'] . '_push.' . $info['extension'];
        $newImg = str_replace($info['basename'], '', $bigImg) . $info['filename'] . '_push.' . $info['extension'];
        if (is_file($newFile)) {
            return $newImg;
        }
        $img = imagecreatefromstring(file_get_contents($bigImgPath));

        // https://raw.githubusercontent.com/ZTEsoft-UED/UEDJCrop/master/fonts/msyhl.ttc
        $font = dirname(dirname(dirname(__FILE__))) . '/public/assets/fonts/msyhl.ttc ';//字体
        echo $font;
        $font = '/Users/fengxuting/workspace/cashbell/public/assets/fonts/msyhl.ttc';
        $black = imagecolorallocate($img, 0, 0, 0);//字体颜色 RGB

        $fontSize = 20;   //字体大小
        $circleSize = 0; //旋转角度
        $left = 100;      //左边距
        $top = 150;       //顶边距

        imagefttext($img, $fontSize, $circleSize, $left, $top, $black, $font, $text);

        list($bgWidth, $bgHight, $bgType) = getimagesize($bigImgPath);
        switch ($bgType) {
            case 1: //gif
                // header('Content-Type:image/gif');
                imagegif($img, $newFile);
                break;
            case 2: //jpg
                // header('Content-Type:image/jpg');
                imagejpeg($img, $newFile);
                break;
            case 3: //png
                // header('Content-Type:image/png');
                imagepng($img, $newFile);
                break;
            default:
                break;
        }
        imagedestroy($img);
        return $newImg;
    }


    public static function hasHttp($url)
    {
        return strpos($url, "https://") === 0 || strpos($url, "http://") === 0;
    }

    /**
     * 静态资源host
     */
    public static function staticHost()
    {
        $host = 'http://' . $_SERVER['SERVER_NAME'];
        $hooks = config('addons.hooks');
        $alioss = isset($hooks['upload_config_init']) && $hooks['upload_config_init'][0] == "alioss" ? true : false;
        $config = get_addon_config('alioss');

        return $alioss ? $config['cdnurl'] : $host;
    }
}